package com.fingard.dsp.bank.directbank.vbao01;

import com.fingard.dsp.bank.directbank.DirectBase;
import com.fingard.text.StringHelper;
import com.fingard.util.SortHelper;
import com.vbao.service.trade.utils.XmlUtils;
import org.dom4j.DocumentException;

import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.*;

public class VBAO01Base extends DirectBase{

	private static final List<String> not_sign_attrs = new ArrayList();

	static {
		not_sign_attrs.add("Sign");
		not_sign_attrs.add("SignType");
		not_sign_attrs.add("BatchBankCode");
		not_sign_attrs.add("ResultCode");
		not_sign_attrs.add("ErrCode");
		not_sign_attrs.add("Description");
	}
	/**
	 * 获取字符编码
	 * @return
	 */
	public String getCharset() {
		return getBankConfig().getCharset("UTF-8", this.reqHeader.transType);
	}
	
	public String getSFTPDir(String p_reqPath) {
		if (p_reqPath.endsWith("/")) {
			return p_reqPath;
		} else {
			return p_reqPath + "/";
		}
	}
	
	public boolean isEachMerInfo() {
		return getBankConfig().getValueAsBool("useEachMerInfo");
	}
	
	/**
	 * 获取对账单用户名密码后缀
	 * 
	 * @param p_merId
	 * @return
	 * @throws Exception
	 */
	public String getMerIdSuffix(String p_merId) throws Exception {
		return getBankConfig().getMapValueByKey("merIdSuffix", p_merId);
	}

    public Map<String, String> removeHead(Map<String, String> tmpMapParams) {
        tmpMapParams.remove("BankCode");
        tmpMapParams.remove("TransType");
        tmpMapParams.remove("CommandCode");
        tmpMapParams.remove("Entity");
        tmpMapParams.remove("POSRecChannel");
        tmpMapParams.remove("BankAccNum");
        return tmpMapParams;
    }

    protected String getSignStr(Map<String, String> mapParams) {
        Map<String, String> signMap = new HashMap<String, String>();

        for (Map.Entry<String, String> entry : mapParams.entrySet()) {
            String name = entry.getKey();
            String value = entry.getValue();

            if (StringHelper.hasAnyChar(value)) {
                signMap.put(name, value);
            }
        }

        // Map排序
        signMap = SortHelper.sortMapByName(signMap);

        // Map转HTTP字符串
        String signStr = "";
        for (String key : signMap.keySet()) {
            signStr += "&" + key + "=" + signMap.get(key);
        }
        signStr = signStr.substring(1);

        return signStr;
    }

	public boolean verifySignature(String returnOriDKPayxml, String password, String InputCharset) {
		Object value = new TreeMap();

		try {
			value = XmlUtils.parseXML2(returnOriDKPayxml, (List)null, (SortedMap)value, true);
			System.out.println("===>value:" + value);
		} catch (DocumentException var6) {
			var6.printStackTrace();
		}

		String mySign = this.getStrMD(this.getSignContent((SortedMap)value) + password, InputCharset);
		System.out.println("mysign:" + mySign);
		return mySign != null && mySign.length() > 0 && ((SortedMap)value).get("Sign") != null && ((String)((SortedMap)value).get("Sign")).length() > 0 && mySign.equals(((SortedMap)value).get("Sign"));
	}

	private String getSignContent(SortedMap<String, ?> receiveData) {
		try {
			List<String> keys = this.getSortKey(receiveData);
			StringBuffer signContent = new StringBuffer("");
			Iterator var5 = keys.iterator();

			while(var5.hasNext()) {
				String key = (String)var5.next();
				Object obj = receiveData.get(key);
				if (obj instanceof String) {
					String content = (String)obj;
					if (content != null && content.length() > 0 && !not_sign_attrs.contains(key) && !content.equals("null") && !"".equals(content)) {
						if (signContent != null && signContent.length() > 0) {
							signContent.append("&");
						}

						if (content != null && content.trim().length() > 0) {
							signContent.append(key).append("=").append(content);
						}
					}
				}
			}

			System.out.println("签名:" + signContent.toString());
			return signContent.toString();
		} catch (Exception var8) {
			var8.printStackTrace();
			return "";
		}
	}

	private List<String> getSortKey(SortedMap<String, ?> receiveData) {
		List<String> attrs = new ArrayList();
		Iterator var4 = receiveData.keySet().iterator();

		while(var4.hasNext()) {
			String key = (String)var4.next();
			attrs.add(key);
		}

		Arrays.sort(attrs.toArray(new Object[0]));
		return attrs;
	}

	private String getStrMD(String str, String InputCharset) {
		if (str == null) {
			return null;
		} else {
			byte[] inByte = null;

			try {
				inByte = str.getBytes(InputCharset);
			} catch (UnsupportedEncodingException var5) {
				var5.printStackTrace();
			}

			byte[] outByte = this.getMD(inByte);
			return this.byteToStr(outByte);
		}
	}

	private byte[] getMD(byte[] inByte) {
		if (inByte == null) {
			return null;
		} else {
			byte[] hash = null;

			try {
				MessageDigest tMessageDigest = MessageDigest.getInstance("MD5");
				tMessageDigest.update(inByte);
				hash = tMessageDigest.digest();
			} catch (NoSuchAlgorithmException var4) {
				var4.printStackTrace();
			}

			return hash;
		}
	}

	private String byteToStr(byte[] b) {
		if (b == null) {
			return null;
		} else {
			String hs = "";

			for(int n = 0; n < b.length; ++n) {
				int v = b[n] & 255;
				if (v < 16) {
					hs = hs + "0";
				}

				hs = hs + Integer.toString(v, 16).toUpperCase();
			}

			return hs;
		}
	}

}
